package com.bailiban.user.controller;

import com.bailiban.common.entity.Result;
import com.bailiban.common.entity.StatusCode;
import com.bailiban.common.util.JwtUtil;
import com.bailiban.user.entity.Admin;
import com.bailiban.user.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhulang
 * @Classname AdminController
 * @Description AdminController
 */
@RestController
@RequestMapping("admin")
public class AdminController {
    @Autowired
    private AdminService adminService;
    @Autowired
    private JwtUtil jwtUtil;

    @GetMapping("{id}")
    public Result findById(@PathVariable String id) {
        Admin admin = adminService.findById(id);
        return new Result(true, StatusCode.OK, "查询成功", admin);
    }

    @PostMapping("add")
    public Result add(@RequestBody Admin admin) {
        adminService.add(admin);
        return new Result(true, StatusCode.OK, "添加成功");
    }

    @PostMapping("login")
    public Result login(@RequestBody Map<String, String> map) {
        String loginname = map.get("loginname");
        String password = map.get("password");
        Admin admin = adminService.login(loginname, password);
        if (admin == null) {
            return new Result(false, StatusCode.LOGINERROR, "登录失败");
        }
        String token = jwtUtil.createJWT(admin.getId(), admin.getLoginname(), "admin");
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("token", token);
        hashMap.put("loginname", admin.getLoginname());
        return new Result(true, StatusCode.OK, "登录成功", hashMap);

    }
}
